<template>
  <div class="app-container">
    <!-- Note that row-key is necessary to get a correct row order. -->

    <div class='search'>
      <div class="row clearfix">
        <div class="row-item fl">
          <span class="row-item-title">时间</span>
          <span class="">
            <el-date-picker
              @change="datepickerChange"
              v-model="tmpParams.timer"
              :type="dateType"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions2"
            />
          </span>
        </div>
        <div class="row-item fl">
          <el-button type="primary" @click="FnSearch">查询</el-button>
        </div>
      </div>
    </div>

    <div class='table-wrap'>
      <Tables ref="Table" :pparams="{...this.params, ...this.tmpParams}" :columns="columns" :url="dataUrl" @tableBubbling="tableBubbling"></Tables>
    </div>

    <Vmask :btnLoading="mask.btnLoading" :maskTitle='mask.title' :maskData='mask.data' :showMask='mask.showMask' :maskWidth='mask.width' @FnMask='FnMask'></Vmask>
    <!-- $t is vue-i18n global function to translate lang (lang in @/lang)  -->
    <!-- <div class="show-d">
      <el-tag style="margin-right:12px;">{{ $t('table.dragTips1') }} :</el-tag> {{ oldList }}
    </div>
    <div class="show-d">
      <el-tag>{{ $t('table.dragTips2') }} :</el-tag> {{ newList }}
    </div> -->
  </div>
</template>

<script>
import { fetchPerson } from '@/api/user'
import { parseTime } from '@/utils'
import Sortable      from 'sortablejs'
import Pagination    from '@/components/Pagination'
import Tables        from '@/components/Table'
import Vmask         from '@/components/Mask'

export default {
  name: 'UserList',
  components: { Pagination, Tables, Vmask },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    let that    = this
    const end   = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    return {
      dataUrl: '/wxRecord/statistics',
      columns: [{
        dataIndex: "nickName",
        title: "昵称"
      }, {
        title: "优惠次数",
        dataIndex: "discountCount"
      }, {
        dataIndex: "originalCount",
        title: "非优惠次数",
      }, {
        dataIndex: "totalFee",
        title: "缴费金额",
      }, {
        dataIndex: "timeEnd",
        title: "使用时间"
      }, {
        align: 'center',
        dataIndex: ['details'],
        title: '操作'
      }],
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '上个月',
          onClick(picker) {
            let myDate = new Date()
            let year   = myDate.getFullYear();
            let startMonth  = myDate.getMonth();
            let endMonth    = myDate.getMonth() + 1;
            if (startMonth == 0) {
              startMonth = 12
            }
            if (startMonth  < 10){
                startMonth  = "0" + startMonth;
            }
            if (endMonth < 10) {
              endMonth      = "0" + endMonth;
            }
            picker.$emit('pick', [new Date(year + '/' + startMonth + '/1'), new Date(new Date(year + '/' + endMonth + '/1') - 1)]);    
          }
        }]
      },
      dateType: 'datetimerange',
      params: {
        pageNum: 1,
        pageSize: 15,
      },
      params2: {
        pageNum: 1,
        pageSize: 15,
      },
      tmpParams: {
        timer: '',
        beiginDate: '',
        endDate: ''
      },
      sortable: null,
      oldList: [],
      newList: [],
      mask: {
        title: '',
        width: '40%',
        btnLoading: false,
        data: {},
        showMask: false
      }
    }
  },
  created() {
    window.__this = this
  },
  methods: {
    async tableBubbling(obj) {
      let type = obj.type
      let content = obj.content ? JSON.parse(JSON.stringify(obj.content)) : false
      let mask = this.mask
      if (type == 'details') {
        this.params2.openid = content.openid
        this.getPerson()
      }
    },
    FnMask(e) {
      let type = e.type
      let content = e.content ? JSON.parse(JSON.stringify(e.content)) : false
      let mask = this.mask

      if (type == 'cancel') {
        mask.showMask = false
        mask.data = {}
      } else if (type == 'pageNum') {
        this.params2.pageNum = content
        this.getPerson()
      } else if (type == 'pageSize') {
        this.params2.pageNum = 1
        this.params2.pageSize = content
        this.getPerson()
      }
    },
    FnSearch() {
      this.$refs['Table'].fetchList()
    },
    async getPerson() {
      let mask      = this.mask 
      let { data }  = await fetchPerson({...this.params2})
      mask.showMask = true
      mask.title    = '个人数据详细'
      mask.data     = {
        PERSON: true, // 个人数据
        list: data.list,
        total: data.total,
        params: this.params2
      }
    },
    datepickerChange(timer) {
      this.tmpParams.beiginDate = parseTime(timer[0])
      this.tmpParams.endDate = parseTime(timer[1])
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
.table-wrap {
  width: 940px
}
</style>